<template>
  <div>
    <el-row :gutter="20" v-if="paginatedRooms.length">
      <el-col :span="8" v-for="room in paginatedRooms" :key="room.id">
        <el-card>
          <template #header>
            <span>{{ room.roomNum }}</span>
          </template>
          <div>
            <p>房型: {{ room.roomType }}</p>
            <p>价格: {{ room.price }}</p>
            <p>入住时间: {{ room.rztime }}</p>
            <p>退房时间: {{ room.tftime }}</p>
            <p>早餐: {{ room.breakFast }}</p>
            <el-button
                v-if="room.status === 'upcoming'"
                type="primary"
                @click="openOrderDialog(room)"
            >订购</el-button>
            <el-button
                v-else
                type="success"
                disabled
            >已订购</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-pagination
        v-if="rooms.length"
        background
        layout="prev, pager, next"
        :total="rooms.length"
        :page-size="pageSize"
        v-model="currentPage"
        @current-change="handlePageChange"
    />
    <el-dialog
        v-model="orderDialogVisible"
        title="选择支付方式"
        @close="handleDialogClose"
    >
      <el-form :model="orderForm">
        <el-form-item label="支付方式">
          <el-select v-model="orderForm.payWay" placeholder="请选择支付方式">
            <el-option label="在线付款" value="在线付款"></el-option>
            <el-option label="到店付款" value="到店付款"></el-option>
            <el-option label="闪付" value="闪付"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="orderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmOrder">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { getRoomsByHotelId, updateRoom } from '@/api/room.js';
import { addHotelOrder } from '@/api/hotelOrder.js';

const route = useRoute();
const rooms = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);

// 获取用户ID
const userInfoString = localStorage.getItem('userInfo');
const userInfo = ref(JSON.parse(userInfoString));
const userId = userInfo.value.id;

const orderDialogVisible = ref(false);
const orderForm = ref({
  payWay: '',
  room: null
});

const fetchRooms = async () => {
  try {
    const response = await getRoomsByHotelId(route.query.hotelId);
    if (response.code === 1) {
      rooms.value = response.data;
    } else {
      console.error('Failed to fetch rooms:', response.msg);
    }
  } catch (error) {
    console.error('Error fetching rooms:', error);
  }
};

const paginatedRooms = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return rooms.value.slice(start, end);
});

const handlePageChange = (page) => {
  currentPage.value = page;
};

const openOrderDialog = (room) => {
  orderForm.value.room = room;
  orderDialogVisible.value = true;
};

const handleDialogClose = () => {
  orderForm.value.payWay = '';
  orderForm.value.room = null;
};

const confirmOrder = async () => {
  const room = orderForm.value.room;
  if (!orderForm.value.payWay) {
    alert('请选择支付方式');
    return;
  }

  try {
    // 更新客房状态为已订购
    const updateResponse = await updateRoom({
      status: 'payed',
      id: room.id
    });

    if (updateResponse.code === 1) {
      // 更新本地状态
      room.status = 'payed';

      // 添加订单
      const orderResponse = await addHotelOrder({
        status: 'upcoming',
        price: room.price,
        userID: userId,
        roomNum: room.roomNum,
        hotelID: route.query.hotelId,
        rztime: room.rztime,
        tftime: room.tftime,
        roomType: room.roomType,
        payWay: orderForm.value.payWay
      });

      if (orderResponse.code === 1) {
        console.log('订单创建成功');
      } else {
        console.error('订单创建失败:', orderResponse.msg);
      }
    } else {
      console.error('更新客房状态失败:', updateResponse.msg);
    }
  } catch (error) {
    console.error('订购客房失败:', error);
  }

  orderDialogVisible.value = false;
};

onMounted(fetchRooms);
</script>

<style scoped>

</style>
